Read N Characters Given Read4 II - Call multiple times

The API: int read4(char *buf) reads 4 characters at a time from a file.

The return value is the actual number of characters read. For example, it returns 3 if there is only 3 characters left in the file.

By using the read4 API, implement the function int read(char *buf, int n) that reads n characters from the file.

Note:

The read function may be called multiple times.

Solution:

  1. /* The read4 API is defined in the parent class Reader4.
  2. int read4(char[] buf); */
  3. public class Solution extends Reader4 {
  4. // a pointer in the buffer
  5. int ptr = 0;
  6. // how many left in the buffer after last call
  7. int left = 0;
  8. // as read() can be called multiple times
  9. // we should only allocate the buffer once
  10. char[] buffer = new char[4];
  11. /**
  12. * @param buf Destination buffer
  13. * @param n Maximum number of characters to read
  14. * @return The number of characters read
  15. */
  16. public int read(char[] buf, int n) {
  17. // end of file flag
  18. boolean eof = false;
  19. // total bytes have been read this time
  20. int total = 0;
  21. while (!eof && total < n) {
  22. // if we still have some leftovers, use them
  23. // otherwise we read another 4 chars
  24. int size = (left > 0) ? left : read4(buffer);
  25. // check if it's the end of the file
  26. eof = (left == 0 && size < 4);
  27. // get the actual count we are going to read
  28. int count = Math.min(size, n - total);
  29. // update the count of leftovers
  30. left = size - count;
  31. // copy
  32. for (int i = 0; i < count; i++)
  33. buf[total++] = buffer[ptr + i];
  34. // update the pointer
  35. ptr = (ptr + count) % 4;
  36. }
  37. return total;
  38. }
  39. }